package main;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.swing.JFileChooser;

/**
 * 
 * Class to act as an interface to the computer's disk. Saves and
 * reads data to and from disk. Works with ContactList, so there
 * is no need to worry about formatting or how saving happens.
 * 
 *@author Michael
 */
public class Disk {
    
    public static final String FILE = "/data.dat";
	
	/**
	 * @return an object ContactList containing previously saved contacts
	 */
	public static ContactList read() {
	    String DefaultFolder=
	            new JFileChooser().getFileSystemView().getDefaultDirectory().toString();
		try {
		    FileInputStream fileIn =
		            new FileInputStream(DefaultFolder+FILE);
		    ObjectInputStream in = 
		            new ObjectInputStream(fileIn);
		    ContactList data = (ContactList) in.readObject();
		    in.close();
		    fileIn.close();
		    return data;
		}catch(IOException i) {
		    
		}catch(ClassNotFoundException c) {
		    c.printStackTrace();
		}
		return new ContactList();
	}
	
	/**
	 * saves to disk a list of contacts from a ContactList object
	 * @param data
	 */
	public static void write(ContactList data) {
	    String DefaultFolder=
	            new JFileChooser().getFileSystemView().getDefaultDirectory().toString();
		try {
		    FileOutputStream fileOut =
		            new FileOutputStream(DefaultFolder+FILE);
		    ObjectOutputStream out =
		            new ObjectOutputStream(fileOut);
		    out.writeObject(data);
		    out.close();
		    fileOut.close();
		}catch(IOException i) {
		    i.printStackTrace();
		}
	}

}
